package com.xb.loan.encryptor.util;


import com.xb.loan.util.log.DefaultLoggerFacotry;
import org.slf4j.Logger;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.LinkedList;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;


public class ClazzUtil {
	
	private static Logger log = DefaultLoggerFacotry.getLogger(ClazzUtil.class);
	
	public static byte[] getClassData(String libPath, String clazzName){
		
		clazzName = clazzName.replace('.', '/') + ".class";
		
		List<File> jarFiles = getJarFiles(new File(libPath));
		
		if(jarFiles == null){
			
			return null;
		}
		
		for (File jarFile : jarFiles) {
			
			try {
				
				byte[] data = getClassDataFromJar(clazzName, new JarFile(jarFile));
				
				if(data != null){
					
					return data;
				}
				
			} catch (IOException e) {
				
				log.error("ClazzUtil.getJarEntryData have exception.",e);
				
				return null;
			}
		}
		
		return null;
	}
	
	private static byte[] getClassDataFromJar(String clazzName, JarFile jarFile){
		
		Enumeration<JarEntry> entries = jarFile.entries();
		
		while(entries.hasMoreElements()){
			
			JarEntry entry = entries.nextElement();
			
			if(entry.getName().equals(clazzName)){
				
				return getJarEntryData(jarFile,entry);
			}
		}
		
		return null;
	}
	
	private static byte[] getJarEntryData(JarFile jarFile, JarEntry entry) {
		
		InputStream in = null;
		
		try {
			
			in = jarFile.getInputStream(entry);
			
			byte[] b = new byte[in.available()];
			
			in.read(b);
			
			return b;
			
		} catch (IOException e) {
			
			log.error("ClazzUtil.getJarEntryData have exception.",e);
		} finally{
			
			if(in != null){
				
				try {
					
					in.close();
				} catch (IOException e) {
					
					log.error("ClazzUtil.getJarEntryData have exception.",e);
				}
			}
		}
		
		return null;
	}

	// 获取文件夹下所有的jar文件
	private static List<File> getJarFiles(File directory){
		
		if(directory == null){
			
			log.info("ClazzUtil.getJarFiles params is null.");
			
			return null;
		}
		
		if(!directory.exists() || directory.isFile()){
			
			log.info("ClazzUtil.getJarFiles file not exists or is not a directory." + directory.getAbsolutePath());
			
			return null;
		}
		
		List<File> allJars = new LinkedList<File>();
		
		File[] files = directory.listFiles();
		
		for (File file : files) {
			
			if(file.isDirectory()){
				
				allJars.addAll(getJarFiles(file));
			} else if(file.getName().endsWith(".jar")){
				
				allJars.add(file);
			}
		}
		
		return allJars;
	}
	
	public static void main(String[] args) {
		
		String className = "org.apache.log4j.Category";
		
		byte[] data = getClassData(Const.LIB_PATH,className);
		
		System.out.println(data.length);
	}
}
